package com.sinvo.oa.filter;

import com.alibaba.fastjson.JSON;
import com.sinvo.oa.result.R;
import com.sinvo.oa.result.ResultCode;
import com.sinvo.oa.util.JwtUtils;
import com.sinvo.oa.util.LoginUserInfoUtils;
import com.sinvo.oa.util.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Description 验证token的过滤器 每次请求都过滤
 */
public class AuthenticationFilter extends OncePerRequestFilter {

    private RedisTemplate redisTemplate;

    public AuthenticationFilter(RedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        //如果是登录接口，直接放行
        if ("/admin/system/index/login".equals(request.getRequestURI()) || "/captcha".equals(request.getRequestURI())) {
            chain.doFilter(request, response);
            return;
        }
        UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
        if (null != authentication) {
            //authentication不为空则放在security上下文中
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);
        } else {
            //否则没有权限
            ResponseUtil.out(response, R.fail(ResultCode.PERMISSION));
        }
    }

    /**
     * 获取UsernamePasswordAuthenticationToken
     * @param request
     * @return UsernamePasswordAuthenticationToken
     */
    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        // header里获取token
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            //不为空 取出数据
            String username = JwtUtils.getUsername(token);
            if (!StringUtils.isEmpty(username)) {
                //ThreadLocal记录当前登录人
                LoginUserInfoUtils.setUserId(JwtUtils.getUserId(token));
                LoginUserInfoUtils.setUsername(username);
                //通过username获取redis 权限数据
                String authString = (String) redisTemplate.opsForValue().get("oa_"+username);
                //为空返回空
                if (StringUtils.isEmpty(authString)){
                    return new UsernamePasswordAuthenticationToken(username, null, Collections.emptyList());
                }
                //字符串转化为目标集合 List<SimpleGrantedAuthority>
                List<Map> mapList = JSON.parseArray(authString, Map.class);
                List<SimpleGrantedAuthority> authorities = new ArrayList<>();
                for (Map map : mapList) {
                    authorities.add(new SimpleGrantedAuthority((String) map.get("authority")));
                }
                System.out.println("权限"+authorities);
                return new UsernamePasswordAuthenticationToken(username,null,authorities);
            }
        }
        return null;

    }
}
